package com.buka.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buka.constants.Constants;
import com.buka.dao.AddressDao;
import com.buka.entity.Address;
import com.buka.interceptor.LoginUserInterceptor;
import com.buka.service.AddressService;
import com.buka.util.JsonData;
import com.buka.vo.AddressVo;
import com.buka.vo.LoginUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 电商-公司收发货地址表(Address)表服务实现类
 *
 * @author makejava
 * @since 2025-07-30 16:34:06
 */
@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, Address> implements AddressService {

    /**
     * 展示用户收件地址 默认地址排在第一位
     *
     * @return
     */
    @Override
    public JsonData listByUser() {

        List<Address> addresses = listWithUser();

        //将数据实体转为视图对象
        List<AddressVo> addressVoList = addresses.stream().map(addr -> {
            AddressVo addressVo = new AddressVo();
            BeanUtils.copyProperties(addr, addressVo);
            return addressVo;
        }).collect(Collectors.toList());

        return JsonData.buildSuccess(addressVoList);
    }

    private List<Address> listWithUser() {
        LoginUserVo loginUserVo = LoginUserInterceptor.threadLocal.get();
        Long id = loginUserVo.getId();
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, id).orderByDesc(Address::getDefaultStatus);
        List<Address> addresses = baseMapper.selectList(queryWrapper);
        return addresses;
    }

    /**
     * 添加新地址，
     * 可以将新添加的地址设置为默认地址，但是默认地址只能有一个，需要数据库中的地址列表默认状态改为0
     * 将当前地址设为默认
     *
     * @param address
     * @return
     */
    public JsonData add(AddressVo address) {
        LoginUserVo loginUserVo = LoginUserInterceptor.threadLocal.get();
        //先要判断新增的地址是不是被设置为默认地址
        if (address.getDefaultStatus() == Constants.ADDRESS_DEFAULT) {
            LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Address::getDefaultStatus, Constants.ADDRESS_STATUS)
                    .eq(Address::getUserId, loginUserVo.getId());
        }
        Address address1 = new Address();
        BeanUtils.copyProperties(address, address1);
        baseMapper.insert(address1);
        return JsonData.buildSuccess();
    }


    public JsonData del(Long id) {
        //当前删除的记录是否为默认地址
        //如果是默认地址 选择数据里中的第一条，设为默认
        //否则直接删除

        LambdaQueryWrapper<Address> queryWrapper = Wrappers.lambdaQuery(Address.class);
        //直接删除
        LoginUserVo loginUserVo = LoginUserInterceptor.threadLocal.get();
        queryWrapper.eq(Address::getId, id).eq(Address::getUserId, loginUserVo.getId());
        baseMapper.delete(queryWrapper);

        //再去查询数据库是否有默认地址，如果没有再设置第一条为默认
        List<Address> addresses = listWithUser();
        if (CollectionUtil.isNotEmpty(addresses)) {
            Optional<Address> first = addresses.stream().filter(e -> e.getDefaultStatus() == Constants.ADDRESS_DEFAULT).findFirst();
            if (!first.isPresent()) {
                Address address = addresses.get(0);
                address.setDefaultStatus(Constants.ADDRESS_DEFAULT);
                updateById(address);
            }
        }

        return JsonData.buildSuccess();
    }
}

